package com.alpha.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.ExamResponse;
import com.alpha.bom.Professor;
import com.alpha.bom.Student;
import com.alpha.dao.ExamResponseDao;
import com.alpha.dao.StudentDao;

/**
 * Servlet implementation class AllResultsServlet
 */
@WebServlet("/AllResultsServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class AllResultsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(ExamResultsServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AllResultsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		HttpSession session = request.getSession();
		Professor professor = null;
		
		if(session.getAttribute("user") != null && session.getAttribute("user") instanceof Professor) {
			professor = (Professor) session.getAttribute("user");
		} else {
			logger.error("Professor not found.");
			response.sendRedirect("Login.jsp?message=Invalid+user.");
			return;
		}
		
		ArrayList<Student> students = null;
		StudentDao sDao = new StudentDao();
		ExamResponseDao erDao = new ExamResponseDao();
		
		ArrayList<ExamResponse> examResponses = new ArrayList<ExamResponse>();
		try {
			students = sDao.retrieveStudentsByProfessorId(professor.getUserId());
			for(Student s:students){
				for(ExamResponse examR: erDao.retrieveExamResponseByStudent(s.getUserId())){
					examResponses.add(examR);
				}
			}
			
			professor.setStudents(students);

			request.setAttribute("examResponses", examResponses);
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
		
		RequestDispatcher dis=request.getRequestDispatcher("AllResults.jsp");
        dis.forward(request, response);
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
